﻿using System;
using System.Web.Security;

namespace Altairis.FluffyCloud.Security {

    public static class MembershipExtensionMethods {

        public static string CreateEmailChangeCode(this MembershipUser user, string newEmail) {
            if (user == null) throw new ArgumentNullException("user");
            if (newEmail == null) throw new ArgumentNullException("newEmail");
            if (string.IsNullOrWhiteSpace(newEmail)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "newEmail");

            return SignedToken.CreateSignedToken(user.UserName.ToLower(), user.Email.ToLower(), newEmail.ToLower());
        }

        public static string CreatePasswordResetCode(this MembershipUser user) {
            if (user == null) throw new ArgumentNullException("user");
            var lastDate = Math.Max(user.LastActivityDate.Ticks, user.LastLoginDate.Ticks);

            return SignedToken.CreateSignedToken(user.UserName.ToLower(), lastDate);
        }

        public static bool VerifyEmailChangeCode(this MembershipUser user, string newEmail, string code) {
            if (user == null) throw new ArgumentNullException("user");
            if (newEmail == null) throw new ArgumentNullException("newEmail");
            if (string.IsNullOrWhiteSpace(newEmail)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "newEmail");
            if (code == null) throw new ArgumentNullException("code");
            if (string.IsNullOrWhiteSpace(code)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "code");

            return code.Equals(user.CreateEmailChangeCode(newEmail), StringComparison.Ordinal);
        }

        public static bool VerifyPasswordResetCode(this MembershipUser user, string code) {
            if (user == null) throw new ArgumentNullException("user");
            if (code == null) throw new ArgumentNullException("code");

            return code.Equals(user.CreatePasswordResetCode(), StringComparison.Ordinal);
        }
    }
}